package com.yuanchu.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.exception.YuanChuException;
import com.yuanchu.store.client.FeignGoodsClient;
import com.yuanchu.store.dao.YoshopCartDao;
import com.yuanchu.store.dto.EditCartParamsDto;
import com.yuanchu.store.dto.GoodsSkuDto;
import com.yuanchu.store.entity.YoshopCartEntity;
import com.yuanchu.store.entity.YoshopGoodsEntity;
import com.yuanchu.store.entity.YoshopUserEntity;
import com.yuanchu.store.entity.YoshopUserGradeEntity;
import com.yuanchu.store.service.YoshopCartService;
import com.yuanchu.store.service.YoshopUserGradeService;
import com.yuanchu.store.service.YoshopUserService;
import com.yuanchu.store.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("yoshopCartService")
public class YoshopCartServiceImpl extends ServiceImpl<YoshopCartDao, YoshopCartEntity> implements YoshopCartService {

    @Resource
    private FeignGoodsClient feignGoodsClient;

    @Resource
    private YoshopUserService userService;
    @Resource
    private YoshopUserGradeService userGradeService;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public Map<String, Object> queryUserCart(Integer userId) {
        // 查询缓存
        String cacheKey = "cart_" + userId;
        if (redisUtils.hasKey(cacheKey)){
            return (Map<String, Object>) redisUtils.get(cacheKey);
        }

        LambdaQueryWrapper<YoshopCartEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopCartEntity::getUserId, userId);
        lqw.eq(YoshopCartEntity::getIsDelete, 0);
        lqw.orderByDesc(YoshopCartEntity::getCreateTime);
        List<YoshopCartEntity> carts = this.list(lqw);

        if (CollectionUtils.isEmpty(carts)) {
            return new HashMap<>();
        }
        carts.forEach(cart -> {
            Integer goodsId = cart.getGoodsId();
            String goodsSkuId = cart.getGoodsSkuId();
            YoshopGoodsEntity goods = feignGoodsClient.queryGoodsInfo(goodsId, goodsSkuId);
            // 设置商品价格
            GoodsSkuDto skuInfo = goods.getSkuInfo();
            String goodsPrice = skuInfo.getGoodsPrice();
            // 获取用户信息
            YoshopUserEntity user = userService.getById(userId);
            // 获取用户会员等级
            YoshopUserGradeEntity userGrade = userGradeService.getById(user.getGradeId());
            // 会员折扣比例
            String equity = userGrade.getEquity();
            Map map = JSON.parseObject(equity, Map.class);
            String gradeRatio = (String) map.get("discount");   // 9.7折
            // 会员折扣价格（原价*97%=现价）
            BigDecimal gradePriceGoods = new BigDecimal(goodsPrice).multiply(new BigDecimal(gradeRatio))
                    .multiply(new BigDecimal("0.1")).setScale(2, RoundingMode.HALF_UP);
            goods.getSkuInfo().setGoodsPrice(String.valueOf(gradePriceGoods));
            cart.setGoods(goods);
        });
        int cartTotal = queryUserCartCount(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", cartTotal);
        map.put("list", carts);

        // 添加缓存
        redisUtils.set(cacheKey, map, 60 * 60 * 24);

        return map;
    }

    @Override
    @Transactional
    public Integer updateCartById(Integer userId, EditCartParamsDto param) {
        Integer goodsId = param.getGoodsId();
        String goodsSkuId = param.getGoodsSkuId();
        Integer goodsNum = param.getGoodsNum();
        YoshopGoodsEntity yoshopGoodsEntity = feignGoodsClient.queryGoodsInfo(goodsId, goodsSkuId);
        if (goodsNum > yoshopGoodsEntity.getSkuInfo().getStockNum()) {
            throw new YuanChuException("很抱歉, 该商品库存数量不足，请重新选择");
        }
        UpdateWrapper<YoshopCartEntity> updateWrapper = new UpdateWrapper<YoshopCartEntity>().eq("goods_id", goodsId)
                .eq("goods_sku_id", goodsSkuId)
                .eq("user_id", userId).eq("is_delete", 0).set("goods_num", goodsNum);

        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new YuanChuException("更新购物车失败");
        }
        // 删除缓存
        redisUtils.del("cart_" + userId);
        // 更新缓存

        return queryUserCartCount(userId);
    }


    @Override
    public Integer clearCart(Integer userId, List<Integer> cartIds, Integer storeId) {
        // this.removeByIds(cartIds);
        UpdateWrapper<YoshopCartEntity> updateWrapper = new UpdateWrapper<YoshopCartEntity>()
                .eq("user_id", userId).eq("is_delete", 0)
                .in("id", cartIds)
                .set("is_delete", 1);
        this.update(updateWrapper);
        // 删除缓存
        redisUtils.del("cart_" + userId);
        int cartTotal = queryUserCartCount(userId);
        return cartTotal;
    }

    @Override
    @Transactional
    public void addCart(Integer userId, EditCartParamsDto param) {
        YoshopCartEntity cart = new YoshopCartEntity();
        BeanUtils.copyProperties(param, cart);
        cart.setUserId(userId);
        cart.setStoreId(10001);
        cart.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        cart.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        this.save(cart);
        // 删除缓存
        redisUtils.del("cart_" + userId);
    }

    @Override
    public int queryUserCartCount(Integer userId) {
        if (userId == null) {
            return 0;
        }
        List<YoshopCartEntity> cartEntities = this.list(new QueryWrapper<YoshopCartEntity>()
                .eq("user_id", userId).eq("is_delete", 0)
        );
        return cartEntities.stream().mapToInt(YoshopCartEntity::getGoodsNum).sum();
    }

    @Override
    public boolean delCartGoods(Integer userId, String cartIds, int storeId) {
        List<Integer> cartIdList = convertCommaSeparatedToIntegerList(cartIds);
        UpdateWrapper<YoshopCartEntity> updateWrapper = new UpdateWrapper<YoshopCartEntity>()
                .eq("store_id", storeId)
                .eq("user_id", userId).eq("is_delete", 0)
                .in("id", cartIdList)
                .set("is_delete", 1);
        // 删除缓存
        redisUtils.del("cart_" + userId);

        return this.update(updateWrapper);
    }

    /**
     * 将逗号分隔的字符串转换为Integer列表
     *
     * @param input
     * @return
     */
    public static List<Integer> convertCommaSeparatedToIntegerList(String input) {
        return Arrays.stream(input.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
    }
}